<!DOCTYPE html>
<html>
    <head>
        <title locale="title">File Operation</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">
        <link rel="stylesheet" href="../../script/semantic/semantic.min.css">
        <script type="text/javascript" src="../../script/jquery.min.js"></script>
        <script type="text/javascript" src="../../script/semantic/semantic.min.js"></script>
        <script type="text/javascript" src="../../script/ao_module.js"></script>
        <script type="text/javascript" src="../../script/applocale.js"></script>
        <style>
            body{
                overflow: hidden;
            }
            .banner{
                /*background-color:#2b4871;*/
                background: rgb(43,72,113);
                background: linear-gradient(153deg, rgba(43,72,113,1) 43%, rgba(141,146,147,1) 100%); 
                height:50px;
                padding:12px;
                padding-left:20px;
                padding-top:16px;
            }

            #opricon{
                position:absolute;
                top:0px;
                right:0px;
                width:80px;
                height:80px;
            }
            .title{
                color:white;
                font-size:130%;
            }
            .content{
                padding:12px;
            }
            .info{
                margin-top:3px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        </style>
    </head>
    <body>
        <div class="banner">
            <div class="title" locale="banner/title">Calculating Operation</div>
            <img id="opricon" src="img/loading.png" class="ui image"></img>
        </div>
        <div class="content">
            <div class="info"><span locale="info/from">From:</span> <span id="src"></span></div>
            <div class="info"><span locale="info/to">To:</span> <span id="dest"></span></div>
            <div class="info"><span locale="info/progress">Progress:</span> <span id="progress"> <i class="loading spinner icon"></i> <span>Calculating</span></div>
            <div class="ui active small progress" style="margin-top:18px;">
                <div id="progressbar" class="bar" style="width:100%; background-color:#4287f5;"></div>
            </div>
            <div id="advanceControlbtns" class="ui right floated small buttons" style="margin-top: -2em; display: none;">
                <div id="pauseButton" locale="button/pause" class="ui basic grey button" onclick="togglePauseTask();">Pause</div>
                <div id="cancelButton" class="ui basic red button" locale="button/cancel" onclick="cancelTask();">Cancel</div>
            </div>
        </div>
        <div class="ui modal" id="duplicateAction">
            <div class="content">
                <div class="description" style="padding: 0px !important;">
                    <p><i class="big exclamation triangle icon"></i> <span locale="dup/question">File with same name already exists. <b>Which action should be taken?</b></span></p><br>
                </div>
            </div>
            <div class="actions">
                <div locale="dup/overwrite" class="ui labeled button" onclick="continueProcess('overwrite');">
                    Overwrite
                </div>
                <div locale="dup/skip" class="ui labeled button" onclick="continueProcess('skip');">
                    Skip
                </div>
                <div locale="dup/renameAndKeep" class="ui labeled button" style="color: #2fb55c;" onclick="continueProcess('keep');">
                    Rename & Keep
                </div>
              
            </div>
        </div>
        <script>
            /*
                ArOZ Online File Operation Listener
                Usage: Pass in the following JSON object as hash with encodeURIComponent after JSON stringify
                {
                    opr: {move / copy / zip / unzip / download / zipAndDown / unzipAndOpen},
                    src: {filelist, allow multiple files},
                    dest: {filepath},
                    
                    //Optional paramters
                    overwriteMode: {skip / overwrite / keep},
                    callbackWindowID: {floatWindow ID},
                    callbackFunction: {target Window Function Name as String}
                }

                **For download opr, it will first buffer into the browser memory.
                It is not recommended for files > 2GB (Firefox Limit)

                Example callbackFunction: "refreshList()" (string)

            */
            var operationConfig = null;
            var opr = "";
            var oprId = "";
            var originalIcon = "";
            var paused = false;
            var maxPathDisplayLength = 40;
            var legacyMode = !('WebSocket' in window || 'MozWebSocket' in window); //Use AJAX instead of WebSocket if legacy mode is activated
            var enterErrorMode = false;

            //Initalized floatWindow events
            ao_module_setFixedWindowSize();
            ao_module_setWindowSize(400,220);
            
            if (applocale){
                //Applocale found. Do localization
                applocale.init("../locale/file_operation.json", function(){
                    applocale.translate();
                    init();
                });
            }else{
                //Applocale not found. Is this a trim down version of ArozOS?
                applocale = {
                    getString: function(key, original){
                        return original;
                    }
                }
                init();
            }

            
            function init(){
                console.log("Checking launch parameters...");
                if (window.location.hash.length > 0){
                    //OK to proceed
                    try{
                        operationConfig = JSON.parse(decodeURIComponent(window.location.hash.substring(1)));
                        
                        //Check if there are any missing paratmers
                        configValid = true;
                        if (typeof operationConfig.opr == "undefined"){ configValid = false; }
                        if (typeof operationConfig.src == "undefined"){ configValid = false; }
                        if (typeof operationConfig.dest == "undefined"){ configValid = false; }
                        
                        if (!configValid){
                            console.log("Invalid file operation config. Please see the file_operation.html source code for the correct config json object.")
                            ao_module_close();
                            return;
                        }

                        //Parse the missing argument if there are any
                        if (typeof operationConfig.overwriteMode == "undefined"){
                            operationConfig.overwriteMode = "skip";
                        }

                        //Update 17-12-2020, ask the user for overwrite mode if file duplicate exists
                        if (operationConfig.overwriteMode == "ask"){
                            //Check if any file duplication before proceeding
                            console.log(operationConfig.src);

                            $.ajax({
                                url: "../../system/file_system/listDir",
                                data: {dir: operationConfig.dest},
                                success: function(filelist){
                                    //Check for duplication
                                    var srcFilenameList = [];
                                    operationConfig.src.forEach(srcpath => {
                                        var filename = srcpath.split("/").pop();
                                        srcFilenameList.push(filename);
                                    })
                                    var duplicateFound = filelist.some(function(file){
                                        return srcFilenameList.includes(file.Filename);
                                    }); 

                                    console.log(filelist);
                                    console.log(operationConfig.src);

                                    if (duplicateFound){
                                        //Duplication found. 
                                        $("#duplicateAction").modal({
                                            closable: false
                                        }).modal("show");

                                    }else{
                                        //Duplication not found. Start the operation with default mode
                                        operationConfig.overwriteMode = "skip";
                                        processOperations(operationConfig);
                                    }


                                }
                            })
                        }else{
                            //All information are defined. Process it now.
                            processOperations(operationConfig)
                        }
                    
                    }catch(ex){
                        //Failed.
                        console.log("Argument parse error", ex);
                    }
                    

                }else{
                    alert("Invalid use of File Operation Listener.")
                    ao_module_close();
                }
            }

            function continueProcess(duplicateMode){
                operationConfig.overwriteMode = duplicateMode;
                $("#duplicateAction").modal("hide");
                processOperations(operationConfig)
            }

            function processOperations(operationConfig){
                //Update the display information
                $("#src").text(operationConfig.src);
                $("#dest").text(operationConfig.dest);
                opr = operationConfig.opr;
                updateTitle(operationConfig.src.length, operationConfig.opr);

                //Check which type of the oprs is about. And assign the related functions to start
                if (operationConfig.opr == "move"){
                    $("#opricon").attr("src","img/move.gif");
                    originalIcon = "img/move.gif";
                    cut(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode);
                
                }else if (operationConfig.opr == "copy"){
                    $("#opricon").attr("src","img/copy.gif");
                    originalIcon = "img/copy.gif"
                    copyopr(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode);
                
                }else if (operationConfig.opr == "zip"){
                    $("#opricon").attr("src","img/zip.gif");
                    originalIcon = "img/zip.gif"
                    zip(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode);
                
                }else if (operationConfig.opr == "unzip"){
                    $("#opricon").attr("src","img/unzip.gif");
                    originalIcon = "img/unzip.gif"
                    unzip(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode);
                }else if (operationConfig.opr == "unzipAndOpen"){
                    $("#opricon").attr("src","img/unzip.gif");
                    originalIcon = "img/unzip.gif"
                    unzip(operationConfig.src, operationConfig.dest, operationConfig.overwriteMode, function(){
                        //Open the target directory

                    });
                }
            }

            //Unzip zip
            function unzip(srcList, dest, overwriteMode, callback=undefined){
                if (legacyMode){
                    //Run in legacy mode
                    requestCSRFToken(function(token){
                        $.ajax({
                            type: 'POST',
                            url: `../../system/file_system/fileOpr`,
                            data: {opr: "unzip" ,src: JSON.stringify(srcList), dest: dest, csrft: token},
                            success: function(data){
                                handleFinish(data);
                            }
                        });
                    });
                    
                }else{
                    //Filter all + sign in the list
                    var filteredSrcList = [];
                    srcList.forEach(src => {
                        filteredSrcList.push(src.split("+").join("{{plug_sign}}"));
                    });

                    //Open WebSocket
                    var endpoint = getWSEndpoint() + `?opr=unzip&src=${encodeURIComponent(JSON.stringify(filteredSrcList))}&dest=${encodeURIComponent(dest)}&existsresp=${overwriteMode}`
                    console.log(endpoint);
                    var ws = new WebSocket(endpoint);

                    ws.onopen = function(){
                        //Do nothing. Just listen to the progress update
                    };

                    ws.onmessage = function (evt) { 
                        var data = evt.data;
                        var progress = JSON.parse(data);
                        console.log(progress);
                        if (progress.oprid != undefined){
                            //This operation is assigned an ongoing task id. Show pause and cancel
                            showPauseCancelButton();
                            oprId = progress.oprid;
                        }else if (progress.Error != ""){
                            //Something went wrong
                            $("#progressbar").css("background-color", "#eb3f28");
                            enterErrorMode = true;
                            handleFinish({error: progress.Error});
                        }else{
                            //Update the progress display
                            var currentSrc = truncate(progress.LatestFile, maxPathDisplayLength);
                            var filteredDest = operationConfig.dest.trim();
                            if (filteredDest.substr(filteredDest.length -1, 1) != "/"){
                                filteredDest += "/"
                            }
                            var currentDest = truncate(filteredDest + progress.LatestFile, maxPathDisplayLength);
                            $("#src").text(currentSrc);
                            $("#dest").text(currentDest);

                            handleProgressUpdate(progress);
                        }
                    };

                    ws.onclose = function() {
                        if (!enterErrorMode){
                            $("#progressbar").css("background-color", "#2bba35");
                            $("#progressbar").css("width", "100%");
                            $("#progress").text("100%");
                            $("#opricon").attr("src", "img/done.png")
                            setTimeout(function(){
                                if (operationConfig.opr == "unzipAndOpen"){
                                    //If open after unzip is required
                                    ao_module_openPath(operationConfig.dest);
                                }
                                ao_module_close();
                            }, 100);
                        }
                    };  

                    ws.onerror = function(event){
                        console.error("WebSocket error observed:", event);
                        legacyMode = true;
                        console.log("Falling back to Legacy Mode");
                        unzip(srcList, dest, overwriteMode, callback);
                    }
                }
            }

            //Create zip
            function zip(srcList, dest, overwriteMode){
                if (legacyMode){
                    //Run in legacy mode
                    requestCSRFToken(function(token){
                        $.ajax({
                            type: 'POST',
                            url: `../../system/file_system/fileOpr`,
                            data: {opr: "zip" ,src: JSON.stringify(srcList), dest: dest, csrft: token},
                            success: function(data){
                                handleFinish(data);
                            }
                        });
                    });
                }else{
                     //Replace all + sign with tag
                    var filteredSrcList = [];
                    srcList.forEach(src => {
                        filteredSrcList.push(src.split("+").join("{{plug_sign}}"));
                    })

                    //Start WebSocket connection
                    var endpoint = getWSEndpoint() + `?opr=zip&src=${encodeURIComponent(JSON.stringify(filteredSrcList))}&dest=${encodeURIComponent(dest)}&existsresp=${overwriteMode}`
                    console.log(endpoint);
                    var ws = new WebSocket(endpoint);
                    var srcZipRoot = "";
                    ws.onopen = function() {
                        console.log("File Operation WebSocket opened")
                        //Emulate the src folder
                        var srcDir = srcList[0].split("/");
                        srcDir.pop();
                        srcDir = srcDir.join("/");
                        srcZipRoot = srcDir;
                        var currentSrc = truncate(srcDir, maxPathDisplayLength);
                        $("#src").text(currentSrc);

                        //Emulate the dest folder
                        var destFolderName = dest.substr(0, dest.length - 1).split('/').pop();
                        destFolderName += ".zip";
                        var currentDest = truncate(dest + destFolderName, maxPathDisplayLength);
                        $("#dest").text(currentDest);

                    };

                    ws.onmessage = function (evt) { 
                        var data = evt.data;
                        var progress = JSON.parse(data);
                        if (progress.oprid != undefined){
                            //This operation is assigned an ongoing task id. Show pause and cancel
                            showPauseCancelButton();
                            oprId = progress.oprid;
                        }else if (progress.Error != ""){
                            //Something went wrong
                            $("#progressbar").css("background-color", "#eb3f28");
                            enterErrorMode = true;
                            handleFinish({error: progress.Error});
                        }else{
                            //Update the progress display
                            var currentSrc = truncate(srcZipRoot + "/" + progress.LatestFile, maxPathDisplayLength);
                            var filteredDest = operationConfig.dest.trim();
                            if (filteredDest.substr(filteredDest.length -1, 1) != "/"){
                                filteredDest += "/"
                            }
                            var currentDest = truncate(filteredDest + progress.LatestFile, maxPathDisplayLength);
                            $("#src").text(currentSrc);
                            $("#dest").text(currentDest);
                            handleProgressUpdate(progress);
                           
                        }
                    };
                            
                    ws.onclose = function() { 
                        //Transfer finished! Set OK and close in 1 second
                        if (!enterErrorMode){
                            $("#progressbar").css("background-color", "#2bba35");
                            $("#progressbar").css("width", "100%");
                            $("#progress").text("100%")
                            handleFinish({});
                        }
                    };

                    ws.onerror = function(event){
                        console.error("WebSocket error observed:", event);
                        legacyMode = true;
                        console.log("Falling back to Legacy Mode");
                        zip(srcList, dest, overwriteMode);
                    }
                }
            }

            function cut(srcList, dest, overwriteMode){
                if (legacyMode){
                    console.log("WebSocket not found, Running in legacy mode");
                    requestCSRFToken(function(token){
                        $.ajax({
                            type: 'POST',
                            url: `../../system/file_system/fileOpr`,
                            data: {opr: "move" ,src: JSON.stringify(srcList), dest: dest,existsresp: overwriteMode, csrft: token},
                            success: function(data){
                                handleFinish(data);
                            }
                        });
                    });

                    
                }else{
                    //Replace all + sign in srclist with {{plus_sign}}
                    var filteredSrcList = [];
                    srcList.forEach(src => {
                        filteredSrcList.push(src.split("+").join("{{plug_sign}}"));
                    })

                    //Use Websocket for operation updates
                    var endpoint = getWSEndpoint() + `?opr=move&src=${encodeURIComponent(JSON.stringify(filteredSrcList))}&dest=${encodeURIComponent(dest)}&existsresp=${overwriteMode}`
                    console.log(endpoint);
                    var ws = new WebSocket(endpoint);
                    ws.onopen = function() {
                        console.log("File Operation WebSocket opened")
                    };
                        
                    ws.onmessage = function (evt) { 
                        var data = evt.data;
                        var progress = JSON.parse(data);
                        if (progress.oprid != undefined){
                            //This operation is assigned an ongoing task id. Show pause and cancel
                            showPauseCancelButton();
                            oprId = progress.oprid;
                        }else if (progress.Error != ""){
                            $("#progressbar").css("background-color", "#eb3f28");
                            enterErrorMode = true;
                            handleFinish({error: progress.Error});
                           
                        }else{
                            var currentSrc = truncate(operationConfig.src + "/" + progress.LatestFile, maxPathDisplayLength);
                            var filteredDest = operationConfig.dest.trim();
                            if (filteredDest.substr(filteredDest.length -1, 1) != "/"){
                                filteredDest += "/"
                            }
                            var currentDest = truncate(filteredDest + progress.LatestFile, maxPathDisplayLength);
                            $("#src").text(currentSrc);
                            $("#dest").text(currentDest);

                            handleProgressUpdate(progress);
                        }
                        
                    };
                        
                    ws.onclose = function() { 
                        //Transfer finished! Set OK and close in 1 second
                        if (!enterErrorMode){
                            $("#progressbar").css("background-color", "#2bba35");
                            $("#progressbar").css("width", "100%");
                            $("#progress").text("100%")
                            handleFinish({});
                        }
                     
                        
                    };

                    ws.onerror = function(event){
                        console.error("WebSocket error observed:", event);
                        console.log("Falling back to Legacy Mode")
                        legacyMode = true;
                        cut(srcList, dest, overwriteMode)
                    }

                }
               
            }

            function copyopr(srcList, dest, overwriteMode){
                if (legacyMode){
                    //Open operation in legacy mode
                    console.log("WebSocket not found, Running in legacy mode");
                    requestCSRFToken(function(token){
                        $.ajax({
                            type: 'POST',
                            url: `../../system/file_system/fileOpr`,
                            data: {opr: "copy" ,src: JSON.stringify(srcList), dest: dest,existsresp: overwriteMode , csrft: token},
                            success: function(data){
                                handleFinish(data);
                            }
                        });
                    });

                    
                }else{
                    var filteredSrcList = [];
                    srcList.forEach(src => {
                        filteredSrcList.push(src.split("+").join("{{plug_sign}}"));
                    })


                   //Use Websocket for operation updates
                   var endpoint = getWSEndpoint() + `?opr=copy&src=${encodeURIComponent(JSON.stringify(filteredSrcList))}&dest=${encodeURIComponent(dest)}&existsresp=${overwriteMode}`
                    var ws = new WebSocket(endpoint);
                    ws.onopen = function() {
                        console.log("File Operation WebSocket opened")
                    };
                        
                    ws.onmessage = function (evt) { 
                        var data = evt.data;
                        var progress = JSON.parse(data);
                        if (progress.oprid != undefined){
                            //This operation is assigned an ongoing task id. Show pause and cancel
                            showPauseCancelButton();
                            oprId = progress.oprid;
                        }else if (progress.Error != ""){
                            $("#progressbar").css("background-color", "#eb3f28");
                            enterErrorMode = true;
                            handleFinish({error: progress.Error});
                        }else{
                            var currentSrc = truncate(operationConfig.src + "/" + progress.LatestFile, maxPathDisplayLength);
                            var filteredDest = operationConfig.dest.trim();
                            if (filteredDest.substr(filteredDest.length -1, 1) != "/"){
                                filteredDest += "/"
                            }
                            var currentDest = truncate(filteredDest + progress.LatestFile, maxPathDisplayLength);
                            $("#src").text(currentSrc);
                            $("#dest").text(currentDest);
                            
                            handleProgressUpdate(progress);
                        }
                        
                    };
                        
                    ws.onclose = function() { 
                        //Transfer finished! Set OK and close in 1 second
                        if (!enterErrorMode){
                            $("#progressbar").css("background-color", "#2bba35");
                            $("#progressbar").css("width", "100%");
                            $("#progress").text("100%");
                            handleFinish({});
                        }
                    };

                    ws.onerror = function(event){
                        console.error("WebSocket error observed:", event);
                        console.log("Falling back to Legacy Mode")
                        legacyMode = true;
                        copyopr(srcList, dest, overwriteMode)
                    }

                }
               
            }

            var truncate = function (fullStr, strLen, separator) {
                if (fullStr.length <= strLen) return fullStr;

                separator = separator || '...';

                var sepLen = separator.length,
                    charsToShow = strLen - sepLen,
                    frontChars = Math.ceil(charsToShow/2),
                    backChars = Math.floor(charsToShow/2);

                return fullStr.substr(0, frontChars) + 
                        separator + 
                        fullStr.substr(fullStr.length - backChars);
                 };

            function getWSEndpoint(){
                //Open opeartion in websocket
                let protocol = "wss://";
                if (location.protocol !== 'https:') {
                    protocol = "ws://";
                }

                var port = window.location.port;
                if (window.location.port == ""){
                    if (location.protocol !== 'https:') {
                        port = "80";
                    }else{
                        port = "443";
                    }
                    
                }

                wsControlEndpoint = (protocol + window.location.hostname + ":" + port + "/system/file_system/ws/fileOpr");
                return wsControlEndpoint;
            }

            function updateTitle(fileNumber, opr){
                var title = "";
                if (opr == "move"){
                    title = applocale.getString("title/moving","Moving ");
                }else if (opr == "copy"){
                    title = applocale.getString("title/copying","Copying ");
                }else if (opr == "zip" || opr == "zipAndDownload"){
                    title = applocale.getString("title/zipping","Zipping ");
                }else if (opr == "download"){
                    title = applocale.getString("title/downloading","Downloading ");
                }else if (opr == "unzip" || opr == "unzipAndOpen"){
                    title = applocale.getString("title/unzipping","Unzipping ");
                }

                title += fileNumber + " ";
                if (fileNumber == 1){
                    title += applocale.getString("title/file"," File");
                }else{
                    title += applocale.getString("title/files"," Files");
                }

                $(".title").text(title);
            }
            
            function handleProgressUpdate(progress){
                if (progress.StatusFlag != undefined){
                    switch (progress.StatusFlag) {
                        case 1:
                            if ($("#opricon").attr("src") != "img/paused.png"){
                                //Show paused UI state
                                $("#opricon").attr("src", "img/paused.png");
                                $("#pauseButton").text(applocale.getString("button/resume","Resume"));
                            }
                            break;
                        case 2:
                        if ($("#opricon").attr("src") != "img/error.png"){
                                $("#opricon").attr("src", "img/error.png");
                            }
                            break;
                        default:
                            if ($("#opricon").attr("src") != originalIcon){
                                //Show 
                                $("#opricon").attr("src",originalIcon);
                                $("#pauseButton").text(applocale.getString("button/pause","Pause"));
                            }
                    }
                }
                $("#progressbar").css("width", progress.Progress + "%");
                $("#progress").text(progress.Progress + "%")
                if (progress.Progress >= 100){
                    //Set progress bar to green
                    $("#progressbar").css("background-color", "#2bba35");
                    $("#progress").text("100%");
                }
            }

            function handleFinish(data){
                $("#advanceControlbtns").find(".button").addClass("disabled");
                if (data.error !== undefined){
                    $("#progressbar").css("background-color","#db2828");
                    $("#progressbar").parent().removeClass('active');
                    $(".title").html(applocale.getString("error/" + data.error,data.error));
                    $("#opricon").attr("src", "img/error.png");
                    enterErrorMode = true;
                    $("#cancelButton").html(applocale.getString("button/cancel", "Cancel"));
                    return
                }else{
                    $("#progressbar").css("background-color","#21ba45");
                    $("#progressbar").parent().removeClass('active');
                    $("#opricon").attr("src", "img/done.png");

                    if (opr == "move" || opr == "copy" || opr == "zip" || opr == "unzip"){
                        //Action completed. close window.
                        setTimeout(function(){
                            //Do callback if exists
                            if (operationConfig.callbackWindowID == "desktop"){
                                //Special call from desktop
                                parent.eval(operationConfig.callbackFunction);
                            }else if (ao_module_virtualDesktop && operationConfig.callbackWindowID !== undefined && operationConfig.callbackFunction !== undefined){
                                var callbackWindowObject = parent.getFloatWindowByID(operationConfig.callbackWindowID)
                                var windowObject = $(callbackWindowObject).find("iframe")[0];
                                if (windowObject == undefined || windowObject == null){
                                    //Caller no longer exists.
                                    
                                }else{
                                    //Caller still exists. Do callback events
                                    //console.log(windowObject.contentWindow, operationConfig.callbackFunction);
                                    windowObject.contentWindow.eval(operationConfig.callbackFunction);
                                }
                                
                            }

                            //If the target or src is desktop, refresh desktop as well
                            if(pathIsOnDesktop(operationConfig.dest) || pathIsOnDesktop(operationConfig.src[0])){
                                if (ao_module_virtualDesktop){
                                    parent.refresh(undefined, true);
                                }
                            }

                            if (!enterErrorMode){
                                ao_module_close();
                                setTimeout(function(){
                                    //If ao_module_close is not working for some reason
                                    open(location, '_self').close();
                                }, 500);
                            }
                        }, 1000);
                    }else if (opr == "download"){
                        //Create download from buffer
                        
                    }else if (opr == "zipAndDown"){
                        //Download
                        
                    }else if (opr == "unzipAndOpen"){
                        //Unzip and open the target directory
                        setTimeout(function(){
                            //Open the target directory
                            ao_module_openPath(operationConfig.dest);
                            //Close the window
                            ao_module_close();
                        }, 1000);
                       
                    }
                }
                console.log(data);
            }

            function pathIsOnDesktop(path){
                var filteredDest = path;
                if (filteredDest.substr(filteredDest.length - 1) == "/"){
                    filteredDest = filteredDest.substr(0, filteredDest.length - 1);
                }
                var dirChunk = filteredDest.split("/");
                console.log(dirChunk);
                if (dirChunk.length == 2 || dirChunk.length == 3){
                    if (dirChunk[0].toLowerCase() == "user:" && dirChunk[1].toLowerCase() == "desktop"){
                        //This is a direct access desktop file
                        return true;
                    }
                }
                return false;
            }

            function requestCSRFToken(callback){
                $.ajax({
                    url: "../../system/csrf/new",
                    success: function(token){
                        callback(token);
                    }
                })
            }

            /*
                Functions related to pause and cancel of the file operations
            */
            
            function togglePauseTask(){
                if (paused){
                    //Resume
                    $.ajax({
                        url: "../../system/file_system/ongoing",
                        method: "POST",
                        data: {"oprid": oprId, "flag": "continue"},
                        success: function(data){
                            if (data.error != undefined){
                                console.log(data.error);
                            }else{
                                paused = false;
                                $("#pauseButton").text(applocale.getString("button/pause","Pause"));
                                $("#opricon").attr("src",originalIcon);
                            }
                        }
                    });
                }else{
                    //Pause
                    $.ajax({
                        url: "../../system/file_system/ongoing",
                        method: "POST",
                        data: {"oprid": oprId, "flag": "pause"},
                        success: function(data){
                            if (data.error != undefined){
                                console.log(data.error);
                            }else{
                                paused = true;
                                $("#opricon").attr("src","img/paused.png");
                                $("#pauseButton").text(applocale.getString("button/resume","Resume"));
                            }
                        }
                    });
                }
                
            }

            //Cancel the current ongoing task
            function cancelTask(){
                $.ajax({
                    url: "../../system/file_system/ongoing",
                    method: "POST",
                    data: {"oprid": oprId, "flag": "cancel"},
                    success: function(data){
                        if (data.error != undefined){
                            console.log(data.error);
                        }else{
                            //Disable further operation untill task cancelled
                            $("#advanceControlbtns").find(".button").addClass("disabled");
                            $("#cancelButton").html(`<i class="ui loading spinner icon"></i>`);
                        }
                    }
                });
            }

            function showPauseCancelButton(){
                ao_module_setWindowSize(400,254);
                $("#progressbar").parent().css({
                    "margin-bottom":"1em"
                });
                $("#advanceControlbtns").show();
            }


            function hidePauseCancelButton(){
                ao_module_setWindowSize(400,220);
                $("#progressbar").parent().css("margin-bottom", "2.5em");
                $("#advanceControlbtns").hide();
            }
        </script>
    </body>
</html>